# 判断--请求方式的封装
import requests
# import urllib3;urllib3.disable_warnings()
# urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from util.decorator import try_run
from logs.user_log import UserLog

class RunMethod:
	def __init__(self):
		# self.ss = requests.session() # 保持会话，保持cookie
		self.ss = requests
		self.log = UserLog().get_log()

	@try_run
	def post_main(self,url,data,headers=None,cookies=None):
		if cookies !=None:
			res = self.ss.post(url=url,data=data,cookies=cookies,verify=True, headers=headers,timeout=3)
		else:
			res = self.ss.post(url=url,data=data,verify=True, headers=headers,timeout=3)
		return res

	@try_run
	def get_main(self,url,data=None,headers=None,cookies=None):
		if cookies !=None:
			res = self.ss.get(url=url,params=data,cookies=cookies,verify=True, headers=headers,timeout=3)
		else:
			res = self.ss.get(url=url,params=data,verify=True, headers=headers,timeout=3)
		return res

	@try_run
	def put_main(self,url, data, headers=None, cookies=None):
		if cookies !=None:
			res = self.ss.put(url=url,data=data,cookies=cookies,verify=True, headers=headers,timeout=3)
		else:
			res = self.ss.put(url=url,data=data,verify=True, headers=headers,timeout=3)
		return res

	@try_run
	def delete_main(self,url,data,headers=None,cookies=None):
		if cookies !=None:
			res = self.ss.delete(url=url,data=data,cookies=cookies,verify=True, headers=headers,timeout=3)
		else:
			res = self.ss.delete(url=url,data=data,verify=True, headers=headers,timeout=3)
		return res

	def run_main(self,method,url,data=None,headers=None,cookies=None):
		if type(cookies) != dict:
			cookies = None
		self.log.debug('\n开始发送请求, 实际请求数据为：\n method: %s \n url: %s \n headers: %s \n data: %s \n cookies: %s' % (
			method, url, headers, data, cookies))
		if method == 'post':
			res = self.post_main(url,data,headers,cookies)
		elif method == 'put':
			res = self.put_main(url,data,headers,cookies)
		elif method == 'delete':
			res = self.delete_main(url,data,headers,cookies)
		else:
			res = self.get_main(url,data,headers,cookies)
		return res
